package com.lhl.jwt.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;

import java.util.Date;

public class JwtUtil {
    private final static String KEY = "FUCKYOU1FUCKYOU2";
    private final static String USER_KEY = "xx1";
    /**
     * 根据用户ID创建token
     * @param userId
     * @return
     */
    public static String createToken(String userId){
        JSONObject jsonObject = JSONUtil.createObj().set(USER_KEY,userId)
                .set("xx2",encryptHex(IdUtil.fastSimpleUUID()))
                .set("xx3",encryptHex(IdUtil.simpleUUID()));
         return JWT.create()
                .setPayload("sub",encryptHex(JSONUtil.toJsonStr(jsonObject)))
                .setExpiresAt(DateUtil.offset(new Date(), DateField.SECOND, 200))
                .setKey(KEY.getBytes())
                .sign();
    }

    public static Boolean checkToken(String token){
        try{
            boolean flg = JWTUtil.verify(token, KEY.getBytes());
            if (flg){
                try{
                    JWTValidator.of(token).validateDate(DateUtil.date());
                }catch(ValidateException v){
                    flg = false ;
                }
            }
            return flg;
        }catch(Exception ex){
            return false;
        }
    }

    /**
     * 加密
     * @param userId
     * @return
     */
    public static String encryptHex(String userId){
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, KEY.getBytes());
        //加密为16进制表示
        return aes.encryptHex(userId);
    }

    /**
     * 解密
     * @param encryptHex
     * @return
     */
    public static String decryptStr(String encryptHex){
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, KEY.getBytes());
        //加密为16进制表示
        return aes.decryptStr(encryptHex, CharsetUtil.CHARSET_UTF_8);
    }

    /**
     * 通过token获得用户id
     * @param token
     * @return
     */
    public static String getUserId(String token){
        final JWT jwt = JWTUtil.parseToken(token);
        JSONObject json = JSONUtil.parseObj(decryptStr(Convert.toStr(jwt.getPayload("sub"))));
        return json.getStr(USER_KEY);
    }

}
